package com.livegoods.service.impl;

import com.livegoods.commons.pojo.LivegoodsPublistMessage;
import com.livegoods.commons.pojo.LivegoodsResult;
import com.livegoods.pojo.House;
import com.livegoods.rabbitmq.PublishMessage;
import com.livegoods.service.BuyActionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

@Service
public class BuyActionServiceImpl implements BuyActionService {

    /**
     *
     * 抢购逻辑
     *
     * 1，从Redis获取当前房屋id的数据
     *      判断房屋id的isRenty状态：
     *      1 : true 已经出租,直接返回用户，下手慢了，已经被预定了
     *      2 : false 房屋没有出租
     *
     * 2，使用RabbitMQ发送消息队列
     *    在队列的接收方处理事情
     *    1，判断房屋库存
     *    2，下单
     *    3，修改MongoDB房屋出租状态
     *    4，同步Redis中房屋出租装填
     *
     *  3，接受返回结果
     *    抢购 预定成功 给用户返回成功信息
     *    抢购 预定失败 给用户返回失败信息
     *
     *
     */

    @Autowired
    private RedisTemplate redisTemplate;


    @Value("${livegoods.redis.house.detail}")
    private String houseKey;


    @Value("${livegoods.rabbitmq.exchange}")
    private String exchange;


    @Value("${livegoods.rabbitmq.buyaction.routingKey}")
    private String routingKey;


    //注入消息对象
    @Autowired
    private PublishMessage publishMessage;


    @Override
    public LivegoodsResult buyaction(String houseId, String user) {
        try {
            ValueOperations vps = redisTemplate.opsForValue();
            House house  = (House) vps.get(houseKey+houseId);
            if(house.isRented()){
                return LivegoodsResult.error("亲，下手慢了。该房屋已经出租了！");
            }

            //创建消息对象: 当前用户抢购某商品的MQ消息对象
            LivegoodsPublistMessage message = new LivegoodsPublistMessage();
            message.setHouseId(houseId);
            message.setUsername(user);

            //发送同步MQ消息，并接收结果
            Boolean  result = (Boolean) publishMessage.syncSenderMessage(exchange, routingKey, message);

            if(result){
                LivegoodsResult ok = LivegoodsResult.ok();
                ok.setMsg("恭喜！预定房屋成功");
                return ok;
            }else{
                return LivegoodsResult.error("亲，下手慢了。该房屋已经出租了！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return LivegoodsResult.error("抢购程序出现异常！");
        }


    }
}
